#include "FileSystemAccess.h"

namespace clovis {

       namespace io {


            FileSystemAccess::FileSystemAccess(){

            }


            core::Tree * FileSystemAccess::Scan ( core::CString path ){
                if (!isDirectory(path))
                    return NULL;

                core::Tree * tmp = new core::Tree( &path );
                treeBrowse(tmp->getRoot());
                return tmp;
            }

            void FileSystemAccess::treeBrowse(core::Node * node){
                struct dirent * lecture;
                DIR * rep;
                core::CString * tmp = core::Converter::convertClovisVariable<core::CString>(node->getValue());
                rep = opendir(tmp->toCharArray());
                core::CString tmp2;
                core::Node * newNode;
                // On parcours le tout
                while ((lecture = readdir(rep))){
                    tmp2 = *tmp + "/" + lecture->d_name;
                    if ((strcmp(lecture->d_name,"."))&&((strcmp(lecture->d_name,"..")))){
                        if (isDirectory(tmp2)){
                            std::cout << "Dossier: " << tmp2.toStdString() << std::endl;
                            newNode = node->addNode(new core::CString(tmp2));
                            treeBrowse( newNode ) ;
                        }else{
                            std::cout << "Fichier: " << tmp2.toStdString() << std::endl;
                            newNode = node->addNode(new core::CString(tmp2));
                        }
                    }
                }
                closedir(rep);
            }

            bool FileSystemAccess::isDirectory( core::CString path ){
                DIR * rep;
                rep = opendir(path.toCharArray());
                if (rep){
                    closedir(rep);
                    return true;
                }else{
                    return false;
                }
            }

       };
};
